<template>
  <div class="pb-16 bg-white relative h-[800px]">
    <!-- Page Loading State -->

    <template v-if="!loading">
      <!-- Header Section -->
      <div class="pt-10 pb-6 bg-gradient-to-b from-grey-lighten-4 to-white">
        <div class="max-w-screen-xl mx-auto px-11">
          <v-breadcrumbs
            :items="[
              { title: '首页', disabled: false },
              { title: data.category, disabled: false },
              { title: data.title, disabled: true },
            ]"
            class="px-0"
          >
            <template #divider>
              <v-icon icon="mdi-chevron-right" size="small" />
            </template>
            <template #title="{ item }">
              <span :class="{ 'text-h6 font-weight-medium': item.disabled }">
                {{ item.title }}
              </span>
            </template>
          </v-breadcrumbs>
        </div>
      </div>

      <div class="w-full max-w-screen-xl mx-auto px-11 flex gap-7">
        <!-- Main Content -->
        <div class="flex-1 min-w-[912px]">
          <v-window show-arrows class="rounded-lg overflow-hidden">
            <template #prev="{ props }">
              <v-btn
                class="z-[1000]"
                density="comfortable"
                icon="mdi-chevron-left"
                variant="tonal"
                @click="props.onClick"
              />
            </template>
            <template #next="{ props }">
              <v-btn
                class="z-[1000]"
                density="comfortable"
                icon="mdi-chevron-right"
                variant="tonal"
                @click="props.onClick"
              />
            </template>

            <v-window-item v-for="(item, index) in mediaList" :key="index">
              <div class="h-[500px] relative">
                <!-- Image Content -->
                <template v-if="item.type === 'image'">
                  <v-img
                    :src="getFullPath(item.src)"
                    cover
                    height="500"
                    class="rounded-lg"
                  >
                    <template #placeholder>
                      <div class="d-flex align-center justify-center fill-height">
                        <v-progress-circular
                          indeterminate
                          color="black"
                        />
                      </div>
                    </template>
                  </v-img>
                </template>

                <!-- Video Content -->
                <videoPlay
                  v-else-if="item.type === 'video'"
                  v-bind="videoOptions"
                  :src="getFullPath(item.src)"
                  :poster="item.poster"
                  class="rounded-lg overflow-hidden"
                />

                <!-- 3D Model Content -->
                <div
                  v-else-if="item.type === 'glb'"
                  class="border rounded-lg overflow-hidden h-full relative"
                >
                  <Obj-model
                    :modelPath="getFullPath(item.src)"
                    :materialPath="1"
                  />
                  <v-overlay
                    :model-value="true"
                    contained
                    class="align-center justify-center"
                    scrim="white"
                  >
                    <v-progress-circular
                      indeterminate
                      color="primary"
                    />
                  </v-overlay>
                </div>
              </div>
            </v-window-item>
          </v-window>

          <v-card variant="text" class="mt-10 text-body-2 text-grey-darken-1">
            {{ data.res_statement }}
          </v-card>
        </div>

        <!-- Sidebar -->
        <div class="w-[412px] flex-shrink-0 space-y-5">
          <!-- Price Card -->
          <v-card class="pa-7">
            <div class="d-flex justify-space-between align-center">
              <div>
                <span class="text-body-2">价格：</span>
                <span class="text-error font-weight-bold">￥</span>
                <span class="text-error font-weight-bold text-h5">
                  {{ price=='0.00'?'免费': price.toFixed(2) }}
                </span>
              </div>
              <div>
                <span class="text-body-2">有效期：</span>
                <span class="font-weight-bold text-h5">{{ lifespan }}</span>
                <span class="font-weight-bold">天</span>
              </div>
            </div>

            <v-btn
              block
              color="black"
              class="mt-5"
              height="50"
              rounded="pill"
              :loading="loading"
              @click="handleDownload"
            >
              立即下载
            </v-btn>
          </v-card>

          <!-- Info Card -->
          <v-card class="pa-7">
            <v-row dense>
              <v-col
                v-for="(item, index) in status"
                :key="index"
                cols="4"
                class="d-flex align-center"
              >
                <span class="text-body-2">{{ item.name }}</span>
                <v-icon
                  :color="item.is_active ? 'success' : 'grey'"
                  icon="mdi-check-circle"
                  size="small"
                  class="ml-1"
                />
              </v-col>
            </v-row>

            <v-divider class="my-5" />

            <div class="text-body-2 whitespace-pre-line">
              {{ data.description }}
            </div>
          </v-card>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useAppStore } from "@/stores/app";
import { getMaterialDetail } from "@/api/material";
import "vue3-video-play/dist/style.css";
import { videoPlay } from "vue3-video-play/dist/index.mjs";
import { getFullPath } from "@/utils/tools";

const route = useRoute();
const router = useRouter();
const appStore = useAppStore();

const loading = ref(true);
const data = ref({ category: "", title: "", description: "" });
const price = ref(0);
const status = ref({});
const lifespan = ref(0);
const mediaList = ref([]);
const second_category = ref([]);

const videoOptions = {
  width: "100%",
  height: "500px",
  color: "#409eff",
  title: "",
  "z-index": 0,
  muted: false,
  webFullScreen: false,
  speedRate: ["0.75", "1.0", "1.25", "1.5", "2.0"],
  autoPlay: false,
  loop: false,
  mirror: false,
  ligthOff: false,
  volume: 0.3,
  control: true,
  controlBtns: [
    "audioTrack",
    "quality",
    "speedRate",
    "volume",
    "setting",
    "pip",
    "pageFullScreen",
    "fullScreen",
  ],
};

onMounted(async () => {
  if (!route.query.id || !route.query.categoryId) {
    loading.value = false;
    return;
  }

  try {
    loading.value = true;
    const category = appStore.materialCategory.find(
      (item) => item.id == route.query.categoryId
    );
    if (category) {
      data.value.category = category.name;
      appStore.activeMaterialCategory = route.query.categoryId;
    }

    const res = await getMaterialDetail({ id: route.query.id });
    updateData(res.data);
  } catch (error) {
    console.error("Failed to fetch material details:", error);
  } finally {
    loading.value = false;
  }
});

function updateData(responseData) {
  data.value.title = responseData.name;
  data.value.description = responseData.desc;
  data.value.res_statement = responseData.res_statement;
  status.value = responseData.options;
  price.value = Number(responseData.price.price);
  lifespan.value = responseData.price.lifespan;
  second_category.value = responseData.second_category;

  mediaList.value = responseData.material_files.map((file) => {
    const fileType = getMediaType(file.static);
    if (fileType === "video") {
      return {
        ...file,
        type: fileType,
        src: file.file_path,
        poster: file.cover_img,
      };
    }
    if (fileType === "glb") {
      return {
        ...file,
        type: fileType,
        src: file.file_path,
        cover_img: file.cover_img,
      };
    }
    if (fileType === "image") {
      return {
        ...file,
        type: fileType,
        src: file.file_path,
      };
    }

    return {
      ...file,
      type: getMediaType(file.static),
      src: file.file_path,
      poster: file.cover_img,
    };
  });
}

function getMediaType(static_type) {
  return (
    {
      1: "image",
      2: "image",
      3: "video",
      4: "glb",
    }[static_type] || undefined
  );
}

function handleDownload() {
  router.push({
    path: "/buy",
    query: {
      img: mediaList.value[0].src,
      id: route.query.id,
      categoryId: route.query.categoryId,
      name: data.value.title,
      fileType: second_category.value.map((item) => item.name).join(","),
      price: price.value,
      lifespan: lifespan.value,
    },
  });
}
</script>

<style scoped>
:deep(.d-player-wrap) {
  border-radius: 8px;
}

:deep(.d-player-video) {
  z-index: 0;
}
</style>
